<template>
  <div>
    <a-form
        auto-label-width
        ref="loginForm"
        :model="form"
        :rules="rules"
        @submit="handleSubmit"
        size="large"
        style="margin-top: 10px"
    >
      <a-form-item
          label="邮&nbsp;&nbsp;&nbsp;&nbsp;箱"
          field="email"
          validate-trigger="blur"
      >
        <a-input
            v-model="form.email"
            :max-length="30"
            show-word-limit
            placeholder="请输入邮箱"
            allow-clear
        />
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="16">
          <a-form-item
              field="captcha"
              label="验证码"
              validate-trigger="blur"
          >
            <a-verification-code
                v-model="form.captcha"
                :length="6"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-button
              type="primary"
              size="large"
              :loading="buttonLoading"
              long
              @click="getCaptcha"
          >
            {{ buttonLoading ? `${loadingTime}秒后获取` : '获取验证码' }}
          </a-button>
        </a-col>
      </a-row>
      <a-button
          html-type="submit"
          style="margin: 20px 0"
          type="primary"
          long
      >
        立即登录
      </a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import request from "../axios/axios";
  import { Message } from '@arco-design/web-vue';
  import {nextTick, onMounted, ref} from "vue";
  import router from "../router";

  const loginForm = ref()
  const buttonLoading = ref(false)
  const loadingTime = ref(60)

  const loading = () => {
    loadingTime.value = 60
    const clean = setInterval(() => {
      loadingTime.value = loadingTime.value - 1;
      if(loadingTime.value <= 0){
        buttonLoading.value = false
        clearInterval(clean);
      }
    }, 1000);
  }

  const captcha = ref({
    captchaId: "",
  })

  const form = ref({
    email: "",
    captcha: ""
  })

  const getCaptcha = () =>{
    if (form.value.email == null || form.value.email === ""){
      loginForm.value.setFields({
        email: {
          status: 'error',
          message: '请先填写邮箱'
        },
      })
      return
    }
    // 校验邮箱格式
    if (!form.value.email.includes("@") || !form.value.email.includes(".")){
      loginForm.value.setFields({
        email: {
          status: 'error',
          message: '请输入正确的邮箱格式'
        },
      })
      return
    }
    buttonLoading.value = true
    loading()
    request.get("/api/auth/send/email",{
      params: {
        email: form.value.email
      }
    }).then(res => {
      if (res.data.success === true){
        Message.success("验证码发送成功！有效期5分钟")
        captcha.value.captchaId = res.data.data.emailId
      }
    })
  }

  const rules = {
    email: [
      {required: true, message: "请输入邮箱", trigger: "blur"},
      {minLength: 6, maxLength: 30, message: "长度为 6 - 30 个字符", trigger: "blur"},
    ],
    captcha: [
      {required: true, message: "请输入验证码", trigger: "blur"},
      {length: 6, message: "长度为 6 个字符", trigger: "blur"}
    ]
  }

  const handleSubmit = ({values, errors}) => {
    if (errors){
      Message.error("请将信息填写完整")
      return
    }
    request.post("/api/auth/login/email", {
      email: form.value.email,
      emailDto: {
        emailCode: form.value.captcha,
        emailId: captcha.value.captchaId
      }
    }).then(res => {
      if (res.data.success === true){
        Message.success("登录成功！")
        localStorage.setItem("token", res.data.data.token)
        nextTick(() => {
          router.replace("/")
        })
      }else {
        form.value.captcha = ""
      }
    })
  }
</script>

<style scoped>

</style>
